package com.infnoon.ojback.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.infnoon.ojback.common.BaseResponse;
import com.infnoon.ojback.common.DeleteRequest;
import com.infnoon.ojback.common.ErrorCode;
import com.infnoon.ojback.common.ResultUtils;
import com.infnoon.ojback.exception.BusinessException;
import com.infnoon.ojback.exception.ThrowUtils;
import com.infnoon.ojback.model.dto.contest.ContestCreateRequest;
import com.infnoon.ojback.model.dto.contest.ContestQueryRequest;
import com.infnoon.ojback.model.dto.contest.ContestRegisterRequest;
import com.infnoon.ojback.model.entity.Contest;
import com.infnoon.ojback.model.entity.Question;
import com.infnoon.ojback.model.entity.User;
import com.infnoon.ojback.model.vo.ContestVO;
import com.infnoon.ojback.service.ContestService;
import com.infnoon.ojback.service.QuestionService;
import com.infnoon.ojback.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 比赛接口
 */
@RestController
@RequestMapping("/contest")
@Slf4j
public class ContestController {

    @Resource
    private UserService userService;

    @Resource
    private QuestionService questionService;

    @Resource
    private ContestService contestService;

    private final static Gson GSON = new Gson();

    /**
     * 创建新比赛
     *
     * @param contestCreateRequest
     * @param request
     * @return
     */
    @PostMapping("/create")
    public BaseResponse<Long> createContest(@RequestBody ContestCreateRequest contestCreateRequest, HttpServletRequest request) {
        if (contestCreateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Contest contest = new Contest();
        BeanUtils.copyProperties(contestCreateRequest, contest);

        List<Question> contestTasks = contestCreateRequest.getContestTasks();
        if (contestTasks != null) {
            contest.setContestTasks(GSON.toJson(contestTasks));
        }
        contestService.validContest(contest);
        User loginUser = userService.getLoginUser(request);
        contest.setUserId(loginUser.getId());
        boolean result = contestService.save(contest);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newContestId = contest.getId();
        return ResultUtils.success(newContestId);
    }

    /**
     * 注册比赛
     *
     * @param contestRegisterRequest
     * @param request
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Contest> registerContest(@RequestBody ContestRegisterRequest contestRegisterRequest, HttpServletRequest request) {
        if (contestRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Contest contest = new Contest();
        BeanUtils.copyProperties(contestRegisterRequest, contest);

        User loginUser = userService.getLoginUser(request);
        contestService.doContestRegister(contestRegisterRequest, loginUser);
        // 保存 报名比赛的用户 的数据
        boolean result = contestService.save(contest);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(contest);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Contest oldContest = contestService.getById(id);
        ThrowUtils.throwIf(oldContest == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        // todo 对、对吗？
        if (!oldContest.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = contestService.removeById(id);
        return ResultUtils.success(b);
    }

//    /**
//     * 更新（仅管理员）
//     *
//     * @param questionUpdateRequest
//     * @return
//     */
//    @PostMapping("/update")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
//        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Contest contest = new Contest();
//        BeanUtils.copyProperties(questionUpdateRequest, contest);
//        List<String> tags = questionUpdateRequest.getTags();
//        if (tags != null) {
//            contest.setTags(GSON.toJson(tags));
//        }
//        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
//        if (judgeCase != null) {
//            contest.setJudgeCase(GSON.toJson(judgeCase));
//        }
//        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
//        if (judgeConfig != null) {
//            contest.setJudgeConfig(GSON.toJson(judgeConfig));
//        }
//        // 参数校验
//        contestService.validContest(contest);
//        long id = questionUpdateRequest.getId();
//        // 判断是否存在
//        Contest oldContest = contestService.getById(id);
//        ThrowUtils.throwIf(oldContest == null, ErrorCode.NOT_FOUND_ERROR);
//        boolean result = contestService.updateById(contest);
//        return ResultUtils.success(result);
//    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Contest> getContestById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Contest contest = contestService.getById(id);
        if (contest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!contest.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(contest);
    }

    /**
     * 根据 id 获取（脱敏）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<ContestVO> getContestVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Contest contest = contestService.getById(id);
        if (contest == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(contestService.getContestVO(contest, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param contestQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<ContestVO>> listQuestionVOByPage(@RequestBody ContestQueryRequest contestQueryRequest,
                                                               HttpServletRequest request) {
        long current = contestQueryRequest.getCurrent();
        long size = contestQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Contest> contestPage = contestService.page(new Page<>(current, size),
                contestService.getContestQueryWrapper(contestQueryRequest));
        return ResultUtils.success(contestService.getContestVOPage(contestPage, request));
    }

//    /**
//     * 分页获取当前用户创建的资源列表
//     *
//     * @param contestQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/my/list/page/vo")
//    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody ContestQueryRequest contestQueryRequest,
//                                                                 HttpServletRequest request) {
//        if (contestQueryRequest == null) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        User loginUser = userService.getLoginUser(request);
//        contestQueryRequest.setUserId(loginUser.getId());
//        long current = contestQueryRequest.getCurrent();
//        long size = contestQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//        Page<Contest> contestPage = contestService.page(new Page<>(current, size),
//                contestService.getContestQueryWrapper(contestQueryRequest));
//        return ResultUtils.success(contestService.getContestVOPage(contestPage, request));
//    }
//
//    /**
//     * 分页获取题目列表（仅管理员）
//     *
//     * @param questionQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/list/page")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody ContestQueryRequest questionQueryRequest,
//                                                           HttpServletRequest request) {
//        long current = questionQueryRequest.getCurrent();
//        long size = questionQueryRequest.getPageSize();
//        Page<Question> questionPage = contestService.page(new Page<>(current, size),
//                contestService.getContestQueryWrapper(questionQueryRequest));
//        return ResultUtils.success(questionPage);
//    }
//
//    // endregion
//
//    /**
//     * 编辑（用户）
//     *
//     * @param questionEditRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/edit")
//    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
//        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        Question question = new Question();
//        BeanUtils.copyProperties(questionEditRequest, question);
//        List<String> tags = questionEditRequest.getTags();
//        if (tags != null) {
//            question.setTags(GSON.toJson(tags));
//        }
//        List<JudgeCase> judgeCase = questionEditRequest.getJudgeCase();
//        if (judgeCase != null) {
//            question.setJudgeCase(GSON.toJson(judgeCase));
//        }
//        JudgeConfig judgeConfig = questionEditRequest.getJudgeConfig();
//        if (judgeConfig != null) {
//            question.setJudgeConfig(GSON.toJson(judgeConfig));
//        }
//        // 参数校验
//        contestService.validQuestion(question, false);
//        User loginUser = userService.getLoginUser(request);
//        long id = questionEditRequest.getId();
//        // 判断是否存在
//        Question oldQuestion = contestService.getById(id);
//        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
//        // 仅本人或管理员可编辑
//        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
//        }
//        boolean result = contestService.updateById(question);
//        return ResultUtils.success(result);
//    }
//
//    /**
//     * 提交题目
//     *
//     * @param questionSubmitAddRequest
//     * @param request
//     * @return 提交记录的 id
//     */
//    @PostMapping("/question_submit/do")
//    public BaseResponse<Long> doQuestionSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
//                                               HttpServletRequest request) {
//        if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
//            throw new BusinessException(ErrorCode.PARAMS_ERROR);
//        }
//        // 登录才能点赞
//        final User loginUser = userService.getLoginUser(request);
//        long questionSubmitId = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);
//        return ResultUtils.success(questionSubmitId);
//    }
//
//    /**
//     * 分页获取题目提交列表（除了管理员外，普通用户只能看到非答案、提交代码等公开信息）
//     *
//     * @param questionSubmitQueryRequest
//     * @param request
//     * @return
//     */
//    @PostMapping("/question_submit/list/page")
//    public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
//                                                                         HttpServletRequest request) {
//        long current = questionSubmitQueryRequest.getCurrent();
//        long size = questionSubmitQueryRequest.getPageSize();
//        // 从数据库中查询原始的题目提交分页信息
//        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size),
//                questionSubmitService.getContestQueryWrapper(questionSubmitQueryRequest));
//        final User loginUser = userService.getLoginUser(request);
//        // 返回脱敏信息
//        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, loginUser));
//    }

}
